package handle

import (
	"SortSet/server/resp"
	"SortSet/server/store"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"strconv"
)

type dataReq struct {
	Start string `json:"start"`
	End   string `json:"end"`
}

func Data(writer http.ResponseWriter, request *http.Request) error {
	requestBytes, err := ioutil.ReadAll(request.Body)
	if err != nil {

		return err
	}
	req := &dataReq{}
	err = json.Unmarshal(requestBytes, req)
	start := req.Start
	end := req.End
	var startI, endI int
	if start == "" {
		startI = 0
	} else {
		startI, err = strconv.Atoi(start)
		if err != nil {
			return err
		}
	}
	if end == "" {
		endI = -1
	} else {
		endI, err = strconv.Atoi(end)
		if err != nil {
			return err
		}
	}
	data, err := store.GlobalSet.Sub(startI, endI)
	if err != nil {
		return err
	}
	count := len(data)

	resp.NewRespAndWriteDirect(
		200,
		"success",
		map[string]interface{}{
			"count": count,
			"list":  data,
		},
		writer)
	return nil
}
